﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using HomeStayWebCP.Models;
using DAL;
using HomeStayWebCP.Models.BusinessObject;
using HomeStayWebCP.Utility;
using System.IO;
using System.Data.SqlClient;

namespace HomeStayWebCP.Controllers
{
    public class PostsController : Controller
    {
        #region Hoandx - Declare

        PostModel Postmodel = new PostModel();

        public static List<String> ListFileNameUpload { get; set; }

        public static string[] Checked { get; set; }

        private string StorageRoot
        {
            get { return Path.Combine(Server.MapPath("~/Content/images/PostImage")); }
        }

        #endregion

        //
        // GET: /Posts/

        public ActionResult Index()
        {
            return View();
        }
     
        public ActionResult ViewPost(int postID)
        {
            string username = null;
            //check if user is login or not/ If login-> enable them to like(if not like this post) or comment
            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                username = HttpContext.Session["username"].ToString();
            }

            //Hoangdx Add session PostID
            HttpContext.Session.Add("PostID", postID);

            PostModel postModel = new PostModel(); //get post detail
            WishlistModel wlModel = new WishlistModel(); 
            UserModel userModel = new UserModel();
            RegionModel regionModel = new RegionModel();
            LikeModel likeModel = new LikeModel();
            ImageModel imageModel = new ImageModel();
            HomeStayTypeModel hsTypeModel = new HomeStayTypeModel();
            CommentModel commentModel = new CommentModel();

            PostItem postDetailInfo = postModel.GetDetailOfPost(postID);
            List<ImageItem> imagesOfPost= imageModel.GetImagesOfPost(postID);
            AuthorInfo author = userModel.GetAuthorOfPost(postID);
            //use to get name of region
            //regionModel.SelectNameFromID(
            int likeNumberofPost = likeModel.CountLikeOfPost(postID);
            List<string> listTypeHomestay = postModel.getHomestayname(postID);
            if(username!= null)
            {
                //like not not
                bool liked = likeModel.CheckCurrentUserLikePost(username, postID);
                ViewBag.liked = liked;
                //Add wishlist or not
                bool addedtoWishlist = wlModel.CheckPostIsAddedToWishlist(username, postID);
                ViewBag.addedtoWishlist = addedtoWishlist;
            }
            
            //getHouseIF from postDetail
            //hsTypeModel.GetNameHomeStayTypeOfHouse(postID);
            List<CommentObject> commentsOfPost = commentModel.GetCommentOfPost(postID);

            //Hoangdx code Comment Function Start

            List<CommentObject> ListCommentView = new List<CommentObject>();
            CommentModel model = new CommentModel();

            //Hoangdx code Paging
            string id = null;
            int count = model.SetCountPaging(5, postID);//Step1: Get so page 
            ViewBag.ListComment = model.GetCommentOfPaing(ref id, postID);//Step 2: get data cho moi page
            ViewBag.count = count;
            ViewBag.page = id;

            //Hoangdx code Comment Function End
            if (listTypeHomestay.Count > 0)
            {
                ViewBag.listTypeHomestay = listTypeHomestay;
            }
            ViewBag.imagesOfPost = imagesOfPost;
            ViewBag.postDetailInfo = postDetailInfo;
            ViewBag.author = author;
            ViewBag.likeNumberofPost = likeNumberofPost;
            ViewBag.commentsOfPost = commentsOfPost;
            if (postDetailInfo != null)
            {
                Session["ContactEmail"] = postDetailInfo.Email;
                Session["PostTitle"] = postDetailInfo.Title;
                if (postDetailInfo.Status == 1)
                {
                    return View();
                }
                else
                {
                    if (username != null && username == author.Username)
                    {
                        return View();
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
            
            //return RedirectToAction("Index", "Home");
           // return View();
        }

        #region Hoangdx Code Posts Function

        #region Event Action View

        //
        // GET: /Posts/

        #region Create Post

        //remove Tag html, js
        static readonly Regex HtmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

        public static string RemoveHtmlTagsUsingCompiledRegex(string htmlString)
        {
            var result = HtmlRegex.Replace(htmlString, string.Empty);
            return result;
        }
        //

        //Step 1 to Create Post
        public ActionResult CreateStep1()
        {
            //New List to save Image FileName 
            ListFileNameUpload = new List<string>();

            //Get Home Stay Type for View
            ViewBag.HomeStayTypeID = GetHomeStayTypeView();

            //Get ProvinceID for showing in combobox
            ViewBag.Province = GetProvineView();

            //Get Type of House
            ViewBag.TypeofHouse = GetTypeOfHouseView();

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateStep1(PostObject dataDTOStep1, FormCollection form)
        {
            dataDTOStep1.Title = RemoveHtmlTagsUsingCompiledRegex(dataDTOStep1.Title);
            dataDTOStep1.Content = RemoveHtmlTagsUsingCompiledRegex(dataDTOStep1.Content);
            dataDTOStep1.House.AddressDetail = RemoveHtmlTagsUsingCompiledRegex(dataDTOStep1.House.AddressDetail);

            //Get Multi-Checkbox from view
            Checked = form.GetValues("HomeStayTypeID");

            //Retun to View CreateStep2 to Create Post with Step 2 + dataDTOStep1 Data from Step 1
            return View("CreateStep2", dataDTOStep1);
        }

        //Step 2 to Create Post
        [HttpPost]
        public ActionResult CreateStep2(PostObject dataDTOStep2, FormCollection form)
        
        {
            //if (dataDTOStep2.House.Area < 5)
            //{
            //    ModelState.AddModelError("House.Area","sai roi");
            //}
            if (ModelState.IsValid)
            {
                if (form["HasGara"] != null)
                {
                    dataDTOStep2.House.HasGara = ((form["HasGara"]).ToString() == "true") ? true : false;
                }
                if (form["HasGarden"] != null)
                {
                    dataDTOStep2.House.HasGarden = ((form["HasGarden"]).ToString() == "true") ? true : false;
                }
                if (form["HasKitchen"] != null)
                {
                    dataDTOStep2.House.HasKitchen = ((form["HasKitchen"]).ToString() == "true") ? true : false;
                }
                dataDTOStep2.Username = HttpContext.Session["username"].ToString();
                Postmodel.CreateNewPost(dataDTOStep2, ListFileNameUpload, Checked);
            }
            //else
            //{
            //    return View("CreateStep2", dataDTOStep2);

            //}
            //return View("ViewMyPost");
            return RedirectToAction("ViewMyPosts");
        }

        public ActionResult ViewMyPost()
        {
            return View();
        }

        #endregion //CreatePost

        #region Edit Post

        //static int _postID = 0;
        public ActionResult EditPost(int id)
        {
            //Kiem tra user hien tai co phai la nguoi tao ra bai post hay ko
            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                //int userID = 0;
                string username = HttpContext.Session["username"].ToString();
                PostModel postModel = new PostModel();
                if (username != null || username != "")
                {
                    List<PostOfUser> l = postModel.GetPostOfUser(username);
                    bool checkExisted = false;
                    foreach (var item in l)
                    {
                        if (item.PostID == id)
                        {
                            checkExisted = true;
                            break;
                        }
                    }
                    if (checkExisted)
                    {
                        //_postID = id;
                        HttpContext.Session.Add("EditPostID", id);// Gan postID khi edit 1 bai post
                        PostObject postObject = new PostObject();

                        //Get Posts to Edit
                        postObject = Postmodel.GetEditPost(id);

                        //Get ProvinceID for showing in combobox
                        ViewBag.Province = GetProvineView();

                        //Get Type of House
                        ViewBag.TypeofHouse = GetTypeOfHouseView();

                        return View(postObject);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

            
        }

        [HttpPost]
        public ActionResult EditPost(PostObject EditDataDTO, FormCollection form)
        {
            //EditDataDTO.PostID = _postID;
            EditDataDTO.PostID = (int.Parse(HttpContext.Session["EditPostID"].ToString()));//Truyen lai PostID khi Edit bai post
            EditDataDTO.Username = HttpContext.Session["username"].ToString();
            if (form["HasGara"] != null)
            {
                EditDataDTO.House.HasGara = true;
            }
            if (form["HasGarden"] != null)
            {
                EditDataDTO.House.HasGarden = true;
            }
            if (form["HasKitchen"] != null)
            {
                EditDataDTO.House.HasKitchen = true;
            }
            Postmodel.UpdatePost(EditDataDTO);
            return RedirectToAction("ViewMyPosts");
        }

        [HttpPost]
        public ActionResult ChangeAvailable(int pID)
        {
            int check = 0;

            check = Postmodel.ChangeAvailable(pID);

            if (Request.IsAjaxRequest())
            {
                return Json(check, "application/json");//gui du lieu tra ve view .bien chuyen la count
            }
            else
            {
                return RedirectToAction("ViewMyPosts");
            }
        }

        [HttpPost]
        public ActionResult DeletePost(int id)
        {
            Postmodel.DeletePost(id);//Delete Post

            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                //int userID = 0;
                string username = HttpContext.Session["username"].ToString();
                PostModel postModel = new PostModel();
                if (username != null || username != "")
                {
                    List<PostOfUser> l = postModel.GetPostOfUser(username);
                    ViewBag.ListPostOfUser = l;
                }
            }

            return PartialView("ViewMyPosts");
        }

        #endregion //EditPost

        #endregion //Event Action View

        #region Get List View

        public List<SelectListItem> GetHomeStayTypeView()
        {
            List<DAL.Post_ListHomeStayTypes_View> listHomeStayTypeDB = Postmodel.GetHomeStayTypes();
            List<SelectListItem> listHomeStayType = new List<SelectListItem>();
            foreach (var list in listHomeStayTypeDB)
            {
                listHomeStayType.Add(new SelectListItem
                {
                    Text = list.Name,
                    Value = list.HomeStayTypeID.ToString()
                });
            }
            return listHomeStayType;
        }

        public List<SelectListItem> GetTypeOfHouseView()
        {
            TypeOfHouseModel typehousemodel = new TypeOfHouseModel();
            List<DAL.TypeOfHous> listtype = typehousemodel.GetTypeofHouse();

            List<SelectListItem> listTypeOfHouseView = new List<SelectListItem>();
            foreach (var type in listtype)
            {
                listTypeOfHouseView.Add(new SelectListItem
                {
                    Text = type.Name,
                    Value = type.TypeOfHouseID.ToString()
                });
            }
            return listTypeOfHouseView;
        }

        public List<SelectListItem> GetProvineView()
        {
            RegionModel model = new RegionModel();
            List<DAL.Region> listprovince = model.SelectProvince();
            List<SelectListItem> listProvinceCbb = new List<SelectListItem>();
            foreach (var reg in listprovince)
            {
                listProvinceCbb.Add(new SelectListItem
                {
                    Text = reg.Name,
                    Value = reg.RegionID.ToString()
                });
            }
            return listProvinceCbb;
        }

        public ActionResult GetDistrictCbb(int province)
        {
            RegionModel model = new RegionModel();
            List<DAL.Region> listDistrict = model.SelectDistrict(province);
            List<SelectListItem> listDistrictView = new List<SelectListItem>();
            if (listDistrict.Count > 0)
            {
                foreach (var dis in listDistrict)
                {
                    listDistrictView.Add(new SelectListItem
                    {
                        Text = dis.Name,
                        Value = dis.RegionID.ToString()
                    });
                }

            }
            else
            {
                listDistrictView.Add(new SelectListItem
                {
                    Text = "Select DistrictID",
                    Value = "-1"
                });

            }
            ViewBag.District = listDistrictView;

            return PartialView("partialGetDistrict");
        }

        #endregion

        #region Upload event
        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpPost]
        public ActionResult UploadFiles()
        {
            var r = new List<ViewDataUploadFilesResult>();

            foreach (string file in Request.Files)
            {
                var statuses = new List<ViewDataUploadFilesResult>();
                var headers = Request.Headers;

                if (string.IsNullOrEmpty(headers["X-File-Name"]))
                {
                    UploadWholeFile(Request, statuses);
                }
                else
                {
                    UploadPartialFile(headers["X-File-Name"], Request, statuses);
                }

                JsonResult result = Json(statuses);
                result.ContentType = "text/plain";

                return result;
            }

            return Json(r);
        }

        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpGet]
        public void Delete(string id)
        {
            var filename = id;
            var filePath = Path.Combine(Server.MapPath("~/Content/images/PostImage"), filename);

            if (System.IO.File.Exists(filePath))
            {
                System.IO.File.Delete(filePath);
                ListFileNameUpload.Remove(filename);
            }
        }

        //DONT USE THIS IF YOU NEED TO ALLOW LARGE FILES UPLOADS
        [HttpGet]
        public void Download(string id)
        {
            var filename = id;
            var filePath = Path.Combine(Server.MapPath("~/Content/images/PostImage"), filename);

            var context = HttpContext;

            if (System.IO.File.Exists(filePath))
            {
                context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                context.Response.ContentType = "application/octet-stream";
                context.Response.ClearContent();
                context.Response.WriteFile(filePath);
            }
            else
                context.Response.StatusCode = 404;
        }

        private string EncodeFile(string fileName)
        {
            return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));
        }

        private void UploadPartialFile(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request");
            var file = request.Files[0];
            var inputStream = file.InputStream;

            var fullName = Path.Combine(StorageRoot, Path.GetFileName(fileName));

            using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write))
            {
                var buffer = new byte[1024];

                var l = inputStream.Read(buffer, 0, 1024);
                while (l > 0)
                {
                    fs.Write(buffer, 0, l);
                    l = inputStream.Read(buffer, 0, 1024);
                }
                fs.Flush();
                fs.Close();
            }
            statuses.Add(new ViewDataUploadFilesResult()
            {
                name = fileName,
                size = file.ContentLength,
                type = file.ContentType,
                url = "/Posts/Download/" + fileName,
                delete_url = "/Posts/Delete/" + fileName,
                thumbnail_url = @"data:image/png;base64," + EncodeFile(fullName),
                delete_type = "GET",
            });
        }

        //UploadLoad And Add Files to List
        private void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses)
        {
            for (int i = 0; i < request.Files.Count; i++)
            {
                var file = request.Files[i];
                string fileRename = System.Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
                var fullPath = Path.Combine(StorageRoot, Path.GetFileName(fileRename));

                file.SaveAs(fullPath);
                ListFileNameUpload.Add(fileRename);

                statuses.Add(new ViewDataUploadFilesResult()
                {
                    name = file.FileName,
                    size = file.ContentLength,
                    type = file.ContentType,
                    url = "/Posts/Download/" + fileRename,
                    delete_url = "/Posts/Delete/" + fileRename,
                    thumbnail_url = @"data:image/png;base64," + EncodeFile(fullPath),
                    delete_type = "GET",
                });
            }
        }

        #endregion

        #endregion

        public ActionResult ViewMyPosts()
        {
            
            //check if user is login or not/ If login-> enable them to like(if not like this post) or comment
            if (HttpContext.Session["username"] != null && !HttpContext.Session["username"].ToString().Equals(""))
            {
                string username = HttpContext.Session["username"].ToString();
                PostModel postModel = new PostModel();
                if (username != null || username != "")
                {
                    List<PostOfUser> l = postModel.GetPostOfUser(username);
                    ViewBag.ListPostOfUser = l;
                }
            }

            return View();
        }
    }

    #region Hoangdx - Class ViewDataUploadFilesResult
    public class ViewDataUploadFilesResult
    {
        public string name { get; set; }
        public int size { get; set; }
        public string type { get; set; }
        public string url { get; set; }
        public string delete_url { get; set; }
        public string thumbnail_url { get; set; }
        public string delete_type { get; set; }
    }
    #endregion
    
    
}
